// Wire Slave Receiver
#include <Wire.h>

#include <Servo.h>
Servo servo1;
Servo servo2;
Servo servo3;

int setvalue1 = 1500;
int setvalue2 = 1500;
int setvalue3 = 1500;

int turnflag1 = 0;
int turnflag2 = 0;
int turnflag3 = 0;

char Receive1;
char Receive2;
char Receive3;
char Receive4;
char Receive5;
char Receive6;
int Mode_Flag;
int cnt = 0;
int savevalue3;


void setup() {
  Wire.begin(1);                // 用#1地址  连接i2c总线
  Wire.onReceive(receiveEvent); // 注册事件 receiveEvent()具体内容见最后

  servo1.attach(2);
  servo2.attach(3);
  servo3.attach(4);
  servo1.writeMicroseconds(1500);
  servo2.writeMicroseconds(1500);
  servo3.writeMicroseconds(1500);

  Serial.begin(115200);           // 启动串行输出 波特率9600
}

void loop() {

  ControlServo(setvalue1, setvalue2, setvalue3);
}


void ControlServo(int value1, int value2, int value3)
{
  int ch_width_1;
  int ch_width_2;
  int ch_width_3;

  // 将PWM信号输出至引脚
  servo1.writeMicroseconds(value1);//写入us值
  servo2.writeMicroseconds(value2);
  servo3.writeMicroseconds(value3);



}
//下面是 从主机接收数据时执行的函数
//此函数注册为事件，注册的位置是： setup()
void receiveEvent(int howMany) {

  Mode_Flag = 0;
  Serial.print("Message is ");
  while (1 < Wire.available()) { // 循环浏览 ，除了最后一个
    char c = Wire.read();        // 以字符形式接收字节
    if (c == 'x')
    {
      Mode_Flag = 1;
    }
    if (c == 'y')
    {
      Mode_Flag = 2;
    }
    if (c == 'z')
    {
      Mode_Flag = 3;
    }
    if (c == 'w')
    {
      Mode_Flag = 4;
    }
    if (c == 's')
    {
      Mode_Flag = 5;
    }
    if (c == 'd')
    {
      Mode_Flag = 6;
    }



    if (Mode_Flag == 1 && c != 'x')
    {
      Receive1 = c;
    }
    if (Mode_Flag == 2 && c != 'y')
    {
      Receive2 = c;
    }
    if (Mode_Flag == 3 && c != 'z')
    {
      Receive3 = c;
    }
    if (Mode_Flag == 4 && c != 'w')
    {
      Receive4 = c;
    }
    if (Mode_Flag == 5 && c != 's')
    {
      Receive5 = c;
    }
    if (Mode_Flag == 6 && c != 'd')
    {
      Receive6 = c;
    }

    //    Serial.println(c);             // 打印出来

  }
  Serial.print(Receive1);
  Serial.print(Receive2);
  Serial.println(Receive3);

  int x = Wire.read();       // 以整数形式接收字节
  if (Receive1 == '+')
  {
    setvalue1 = 1200;
  }
  else if (Receive1 == '-')
  {
    setvalue1 = 1800;
  }
  else
  {
    setvalue1 = 1500;
  }


  if (Receive2 == '+')
  {
    setvalue2 = 1200;
  }
  else if (Receive2 == '-')
  {
    setvalue2 = 1800;
  }
  else
  {
    setvalue2 = 1500;
  }


  if (Receive3 == '+')
  {
    setvalue3 = 1200;
  }
  else if (Receive3 == '-')
  {
    setvalue3 = 1800;
  }
  else
  {
    setvalue3 = 1500;
  }


  delay(1000);


}
